﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XXF.BaseService.ConfigManager.Model;

namespace XXF.BaseService.ConfigManager.SystemRuntime
{
    [Serializable]
    public class ConfigInfoModel
    {
        public tb_config_model configmodel { get; set; }
        public  Dictionary<string,tb_loadbalance_model> loadbalacemodels { get; set; }
        public Dictionary<string, tb_failover_model> failovermodels { get; set; }

        public string Value()
        {
            //故障中则读取,故障配置
            if (configmodel.failoversequence > 0)
            {
                return failovermodels[configmodel.failoversequence.ToString()].value;
            }
            //负载均衡则读取，负载均衡配置
            if (configmodel.loadbalancealgorithmenum >= 0&&this.loadbalacemodels!=null)
            {
                return LoadBalanceGorithmenum();
            }
            return configmodel.configvalue;
        }

        public string LoadBalanceGorithmenum()
        {
            int allboost = 0;
            foreach (var m in loadbalacemodels)
            {
                allboost += m.Value.boostpercent;
            }
            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int rdboost = rd.Next(0, allboost) + 1;//1-100
            int boost = 0;
            //俄罗斯罗盘的方式
            foreach (var m in loadbalacemodels)
            {
                boost += m.Value.boostpercent;
                if (boost >= rdboost)
                {
                    return m.Value.value;
                }
            }
            LogHelper.Debug(string.Format("负载均衡算法,总权重:{0},随机权重:{1}", allboost, rdboost));
            throw new ConfigException(string.Format("负载均衡算法错误,总权重:{0},随机权重:{1}", allboost, rdboost));
        }
    }
}
